package op3;

public class OPT {
    public static final int N = 3;
    private Object[] array = new Object[N];
    private int size;
    private int[] longest = new int[N];
    public OPT() {
    }
    public boolean isOutOfBoundary() {
        return size >= N;
    }
    public int indexOfElement(Object o) {
        for(int i=0; i<N; i++) {
            if(o == array[i]) {
                return i;
            }
        }
        return -1;
    }
    /**
     * 找出未来最久的时间会被调用的元素的序号
     * @param k 开始调用时的下标
     * @param procList 整个进程对列的调用过程
     * @return
     */
    private int findTransIndex(final int k, final Object[] procList) {
        int transIndex = 0;
        int longest2 = 0;
        for(int j=0; j<size; j++) {
            longest[j] = Integer.MAX_VALUE;
        }
        for(int i=k+1; i<procList.length; i++) {
            for(int j=0; j<size; j++) {
                if(procList[i] ==  array[j]) {
                    if(longest[j] == Integer.MAX_VALUE) {
                        longest[j] = i;
                        if(longest2 < longest[j])
                            transIndex = j;
                    }
                }
            }
        }
        for(int j=0; j<size; j++) {
            if(longest[j] == Integer.MAX_VALUE) {
                transIndex = j;
                break;
            }
        }
        return transIndex;
    }
    public Object push(Object[] procList, int k) {
        int t = -1;
        if(!isOutOfBoundary() && indexOfElement(procList[k]) == -1){
            array[size] = procList[k];
            size++;
        } else if(!isOutOfBoundary() && indexOfElement(procList[k]) != -1) {
            t = indexOfElement(procList[k]);
        } else if(isOutOfBoundary() && indexOfElement(procList[k]) == -1){
            int transIndex = findTransIndex(k, procList);
            array[transIndex] = procList[k];
            t = transIndex;
        }
        if(-1 == t) {
            return null;
        }
        return array[t];
    }
    /**
     * 输出内存区中的各数据
     */
    public void showMemoryBlock() {
        for(int i=0; i<size; i++) {
            System.out.print(array[i] + "  ");
        }
    }
    public static void main(String[] args) {
        Integer[] iter = {7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1};
        OPT optimal = new OPT();
        for(int i=0; i<iter.length; i++) {
            optimal.push(iter, i);
            optimal.showMemoryBlock();
            System.out.println();
        }
    }
}